<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据结构之字典</title>
</head>
<body>
  <script type="text/javascript">
    function Dictionary() {
      this.dataStore = new Array();
      this.add = add;
      this.find = find;
      this.remove = remove;
      this.count = count;
      this.clear = clear;
      this.showAll = showAll;
    }

    // 向字典中添加元素
    function add(key, value) {
      this.dataStore[key] = value;
    }

    // 查询字典中的某个元素
    function find(key) {
      return this.dataStore[key];
    }

    // 删除字典中的某个元素
    function remove(key) {
      delete this.dataStore[key];
    }

    // 查询字典中的元素个数
    function count() {
      return Object.keys(this.dataStore).length;
    }

    // 清空字典
    function clear() {
      var dataKeys = Object.keys(this.dataStore);
      for (var key in dataKeys) {
        delete this.dataStore[dataKeys[key]];
      }
    }

    // 打印整个字典信息
    function showAll() {
      var dataKeys = Object.keys(this.dataStore);
      for (var key in dataKeys) {
        console.log(dataKeys[key] + ' -> ' + this.dataStore[dataKeys[key]]);
      }
    }

    var goods = new Dictionary();
    goods.add('first', 456);
    goods.add('second', 145);
    goods.add('third', 954);
    console.log(goods.find('second'));
    goods.showAll();
    console.log(goods.count());
    goods.remove('second');
    goods.showAll();
    goods.clear();
    console.log(goods.count());
  </script>
</body>
</html>